<?php

class TemplateImporter
{
	var $db_info = null;
	var $project_root_path = null;
	var $mappings = null;
	var $do_confirm = null;
	var $db_link = null;
	
	/**
	 *
	 */
	function __construct($db_info, $project_root_path, $mappings, $do_confirm=false)
	{
		if (empty($db_info) || empty($project_root_path) || empty($mappings))
		{
			print("[TemplateImporter] error: missing one or more required parameters\n");
			if (empty($mappings))
			{
				print("No mappings provided\n");
			}
			if (empty($project_root_path))
			{
				print("No project root path provided\n");
			}
			if (empty($db_info))
			{
				print("No dbinfo provided\n");
			}
			exit();
		}
		
//		print_r($mappings);

		$this->db_info = $db_info;
		$this->project_root_path = $project_root_path;
		$this->mappings = $mappings;
		$this->do_confirm = $do_confirm;
		
		print("Connecting to host: {$db_info['hostname']}, with user {$db_info['username']} (pass: {$db_info['password']})\n");
		
		$this->db_link = mysql_connect($db_info['hostname'], $db_info['username'], $db_info['password'])
			or die('[TemplateImporter] error: could not connect to server: ' . mysql_error());

		print("Selecting database: {$db_info['database']}\n\n");
			
		mysql_select_db($db_info['database']) 
			or die('[TemplateImporter] error: could select datbase: ' . mysql_error());
	}
	
	/**
	 *
	 */
	function import()
	{
		$sql = array();
		$display_queries = array();
		$sites = $this->get_site_ids();
		
		$templates_changed = 0;
		
		foreach ($this->mappings as $map)
		{
			$this->validate_mapping($map); // quits with an error if there is a problem
			$site = $map['site'];
			$path = $map['path'];
			$name = $map['template_name'];
			$group = $map['template_group'];
			$index_group = $map['template_group_index'];
			$type = $map['template_type'];
			$allow_php = $map['allow_php'];
			$php_parse_location = $map['php_parse_location'];
			$create_pointer_pages = $map['create_pointer_pages'];
			$create_pointers_as_index_pages = $map['create_pointers_as_index'];
			$pointer_type = $map['pointer_template_type'];
			
			$data = $this->convert_chars_for_mysql(file_get_contents($this->project_root_path . "/" . $path));
			/**if (empty($data))
			{
				exit("[TemplateImporter] error: template file was empty: $this->project_root_path/$path\n");
			}**/
			
			$shell_site_id = $sites[$site];
			
			//template group/s
			if($create_pointer_pages)
			{
				foreach($sites as $site_name => $site_id)
				{
					$group_id = $this->get_group_id($group, $site_id);
					if(!empty($group) && empty($group_id))
					{
						$this->insert_template_groups($site_id, $group);
					}
					
					//set template group as index
					if(!empty($index_group))
					{
						$this->set_group_site_default($site_id, $group, $index_group);
					}
				}
			}
			else
			{
				$group_id = $this->get_group_id($group, $shell_site_id);
				if(!empty($group) && empty($group_id))
				{
					$this->insert_template_groups($shell_site_id, $group);
				}
				
				//set template group as index
				if(!empty($index_group))
				{
					$this->set_group_site_default($site_id, $group, $index_group);
				}
			}
			
			//template/s
			$templates_changed += $this->insert_or_update_template($shell_site_id, $group, $name, $type, $allow_php, $php_parse_location, $data, $path);
			
			if($create_pointer_pages)
			{
				$template_name = $create_pointers_as_index_pages ? 'index' : $name;
				$data = $this->convert_chars_for_mysql("{embed=$site:$group/$name}");
				
				foreach($sites as $site_name => $site_id)
				{
					if($site_id != $shell_site_id)
					{
						$type = $pointer_type ? $pointer_type : $type;
						$templates_changed += $this->insert_or_update_template($site_id, $group, $template_name, $type, $allow_php, $php_parse_location, $data, $path);
					}
				}
			}
			
		}
		
		print("$templates_changed template(s) were created/updated\n\n");
	}
	
	function insert_or_update_template($site_id, $group_name, $name, $type, $allow_php, $php_parse_location, $data, $path)
	{
		$query = "";
		$data_part = "";
		$where_part = "";
		
		$group_id = $this->get_group_id($group_name, $site_id);
		
		if($this->template_exists($group_id, $name, $site_id)) // determine whether to do an update or insert
		{
			$query = "UPDATE exp_templates SET ";
			$where_part = " WHERE template_name = '$name' AND site_id = $site_id AND group_id = $group_id";
		}
		else
		{
			$query = "INSERT INTO exp_templates SET ";
		}
		
		$query .= "template_name = '$name', template_type = '$type',";
		
		if(!empty($allow_php))
		{
			$query .= " allow_php = '$allow_php',";
		}
		
		if(!empty($php_parse_location))
		{
			$query .= " php_parse_location = '$php_parse_location',";
		}
		
		$query .= "site_id = $site_id, group_id = '$group_id', ";
		
		$display_query = $query ." template_data = '[contents of $this->project_root_path/$path]'" . $where_part;
		
		$query .= "template_data = '$data'";
		
		$query .= $where_part;
		
		if($this->do_confirm)
		{
			$affected = $this->execute_query($query);
			if ($affected > 0)
			{
				print("Running query for real:\n$display_query\n");
				print("[$affected rows affected]\n\n");
			}
		}
		else
		{
			print("Query preview:\n$display_query\n\n");
		}
		
		return $affected;
	}
	
	
	function insert_template_groups($site_id, $group_name)
	{
		$query = "INSERT INTO exp_template_groups SET site_id = $site_id, group_name = '".$this->convert_chars_for_mysql($group_name)."'";
		
		if($this->do_confirm)
		{
			print("Running query for real:\n$query\n");
			$affected = $this->execute_query($query);
			print("[$affected rows affected]\n\n");
		}
		else
		{
			print("Preview query:\n$query\n\n");
		}
	}
	
	/**
	 * sets the site index group
	 */
	function set_group_site_default($site_id, $group_name, $index_group)
	{
		$not_index_group = $index_group == 'y' ? 'n' : 'y';
		
		$reset_query = "UPDATE exp_template_groups SET is_site_default = '$not_index_group' WHERE site_id = $site_id";
		
		$query = "UPDATE exp_template_groups SET is_site_default = '$index_group' WHERE site_id = $site_id AND group_name = '".$this->convert_chars_for_mysql($group_name)."'";
		
		if($this->do_confirm)
		{
			print("Running query for real:\n$reset_query\n");
			$affected = $this->execute_query($reset_query);
			print("[$affected rows affected]\n\n");
			
			print("Running query for real:\n$query\n");
			$affected = $this->execute_query($query);
			print("[$affected rows affected]\n\n");
		}
		else
		{
			print("Preview query:\n$reset_query\n\n");
			print("Preview query:\n$query\n\n");
		}
	}
	
	/**
	 *
	 */
	function validate_mapping($map, $ignore_file=false)
	{
		$message = "";
	
		$required_params = array('template_name', 'template_group', 'template_type', 'path');
	
		foreach ($required_params as $param)
		{
			if (empty($map[$param]))
			{
				$message = "required map parameter '$param' was missing";
				break;
			}
		}	

		$file = $this->project_root_path . "/" . $map['path'];
		
		if (!file_exists($file) && !$ignore_file)
		{
			$message = "could not find template path '$file'";
		}
		
		if (!empty($message))
		{
			exit("[TemplateImporter] error - bad template mapping: $message\n");
		}
	}
	
	/**
	 *
	 */
	function get_group_id($group_name, $site_id)
	{
		$group_id = '';
		
		$query = "SELECT group_id FROM exp_template_groups WHERE site_id = $site_id AND group_name = '$group_name'";
		
		if ($site_id != '')
		{
			$query .= " AND site_id = $site_id";
		}

		$rows = $this->get_query_rows($query);
//		print_r($rows);//TMP
		
		$group_id = $rows[0]['group_id'];
		
		return $group_id;
	}
	
	/**
	 * Returns array of site ids and names
	 */
	function get_site_ids()
	{
		$sites = array();
		
		$query = "SELECT site_id, site_name FROM exp_sites ORDER BY site_id";
		
		$rows = $this->get_query_rows($query);

		foreach($rows as $row)
		{
			$sites[$row['site_name']] = $row['site_id'];
		}
		
		return $sites;
	}
	
	// query the database and see if the named template exists
	function template_exists($group_id, $name, $site_id)
	{
		$query = "SELECT * FROM exp_templates WHERE site_id = $site_id AND group_id = '$group_id' AND template_name = '$name'";
		//print("query: $query\n");//TMP
		
		$rows = $this->get_query_rows($query);
		
		$exists = (sizeof($rows) > 0);
		
		return $exists;
	}
	
	/**
	 *
	 */
	function get_query_rows($query)
	{
		$rows = array();
	
		$result = mysql_query($query, $this->db_link) 
			or die('[TemplateImporter] error: Query failed: ' . mysql_error());

		if (mysql_num_rows($result) > 0)
		{
			while (($row = mysql_fetch_assoc($result)))
			{
				$rows[] = $row;
			}
		}
		
		return $rows;
	}
	
	/**
	 *
	 */
	function execute_query($query)
	{
		$result = mysql_query($query, $this->db_link) 
			or die('[TemplateImporter] error: Query failed: ' . mysql_error());		
			
		$affected = mysql_affected_rows($this->db_link);

		return $affected;
	}
	
	/**
	 * Need to convert the characters on import, just in case. 
	 */
	function convert_chars_for_mysql($data)
	{
		$data = mysql_real_escape_string($data);
		
		$encoding = mb_detect_encoding($data, 'UTF-8, ISO-8859-1');
		//print($encoding);//TMP
		$data = mb_convert_encoding($data, "UTF-8", $encoding);
		//$data = iconv("ISO-8859-1", "UTF-8", $data);
		
		return $data;
	}
	
}


?>